#include<iostream>
#include<cstdio>
#include<unistd.h>
#include<cassert>
#include<sys/types.h>
#include<sys/wait.h>
#include<string>
#include<cstring>
using namespace std;
//父进程读取，子进程写入
int main()
{
    //创建Pipe，打开读写端
    int fds[2];
    int n=pipe(fds);
    assert(n==0);
    //第二步：fork
    pid_t id=fork();
    assert(id>=0);
    if(id==0)
    {
        //子进程
        //子进程写入
        close(fds[0]);
        //string msg="hello , i am child";
        const char* s="我是子进程，我正在给你发消息";
        int cnt=0;
        while(true)
        { 
            cnt++;
            char buffer[1024];
            snprintf(buffer,sizeof buffer,"child->parent say:%s[%d][%d]",s,cnt,getpid());
            write(fds[1],buffer,strlen(buffer));
            //写端写满时，在写会阻塞
            //sleep(1);//细节，每隔1s发一次信息
            break;
        }
        
        close(fds[1]);
        cout<<"子进程关闭自己的写端"<<endl;
        exit(0);
    }
    //父进程
    //父进程进行读取
    close(fds[1]);
    while(true)
    {
        char buffer[1024];
        //如果管道中没数据了，读端在读，默认会直接阻塞当前正在读取的进程
        ssize_t s=read(fds[0],buffer,sizeof(buffer)-1);
        if(s>0)
        {
        buffer[s]=0;
        std::cout<<"Get Message#"<<buffer<<"   |  my pid"<<getpid()<<std::endl;
        }
        else if(s==0)
        {
          //读到文件结尾
          cout<<"read: "<<s<<endl;
          break;
        }
    }
    n=waitpid(id,nullptr,0);
    assert(n==id);
    // std::cout<<"fds[0]"<<fds[0]<<std::endl;
    // std::cout<<"fds[1]"<<fds[1]<<std::endl;
    //[0]:读取
    //[1]:写入
    close(fds[0]); 
    return 0;
}